package com.sgb.knowledgeshare.view.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.SparseIntArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.aliyun.vod.common.utils.DateUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.sgb.knowledgeshare.R;
import com.sgb.knowledgeshare.ShareConfig;
import com.sgb.knowledgeshare.entity.VideoCommentListEntity;
import com.sgb.knowledgeshare.view.activity.ShareUserActivity;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.recyclerview.adapter.BaseRecycleAdapter;
import com.swgk.core.recyclerview.adapter.ItemViewHolder;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by：冯齐 on 2020/11/13 14:51
 * Description：评论的adapter
 */
public class CommentAdapter extends BaseRecycleAdapter<VideoCommentListEntity.RecordsBeanX> {

    private CommentCallback callback;
    private SparseIntArray mPageArray = new SparseIntArray();
    public int mCurQuePos;
    public int mCurQueChildPos;
    private int mType; // 0:默认 1：一级回复 2： 二级回复
    private Map<String, Object> mQueMap = new HashMap<>();
    private String createUser;
    private boolean isFirst;
    private int type;
    private String ids;

    private boolean isVisibleMoreText = false;

    public CommentAdapter(Context context, List<VideoCommentListEntity.RecordsBeanX> datas, String createUser, int Type, String id) {
        super(context, R.layout.item_comment, datas);
        this.createUser = createUser;
        isFirst = true;
        type = Type;
        this.ids = id;
    }

    @Override
    public void onBindViewHolder(ItemViewHolder holder, @SuppressLint("RecyclerView") int position) {
        super.onBindViewHolder(holder, position);
        VideoCommentListEntity.RecordsBeanX recordsBean = datas.get(position);
        ImageView commentLogo = holder.itemView.findViewById(R.id.comment_loge);//头像
        TextView commentName = holder.itemView.findViewById(R.id.comment_name);//名称
        TextView commentContent = holder.itemView.findViewById(R.id.comment_content);//内容
        TextView commentTime = holder.itemView.findViewById(R.id.comment_time);//时间
        LinearLayout llSeeMore = holder.itemView.findViewById(R.id.ll_see_more);//查看更多
        TextView unwindNumReply = holder.itemView.findViewById(R.id.unwind_num_reply);//多少条评论
        RecyclerView listView = holder.itemView.findViewById(R.id.listView);//二级评论列表
        LinearLayout llTwoSeeMore = holder.itemView.findViewById(R.id.ll_two_see_more);//二级查看更多布局
        TextView unwindTwoNumReply = holder.itemView.findViewById(R.id.unwind_two_num_reply);//二级查看更多
        ImageView imJiantou = holder.itemView.findViewById(R.id.im_jiantou);//二级查看更多图标
        TextView oneAuthor = holder.itemView.findViewById(R.id.one_author);//是否是作者
        TextView commentReply = holder.itemView.findViewById(R.id.comment_reply);//回复
        LinearLayout llCommentZan = holder.itemView.findViewById(R.id.ll_comment_zan);//一级点赞
        TextView commentZanNum = holder.itemView.findViewById(R.id.comment_zan_num);//一级点赞数量
        ImageView imCommentZan = holder.itemView.findViewById(R.id.im_comment_zan);//一级点赞布局
        LinearLayout llContentbg = holder.itemView.findViewById(R.id.ll_contentbg);//一级点赞布局
        //一级头像
        Glide.with(context).load(recordsBean.getImg() + "")
                .apply(RequestOptions.bitmapTransform(new CircleCrop()).placeholder(R.mipmap.share_def_photo))
                .into(commentLogo);
        //头像点击跳转到用户中心界面
        commentLogo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareUserActivity.start(context, recordsBean.getUser());
            }
        });
        //用户名称
        commentName.setText(recordsBean.getUserName() + "");
        //一级评论内容
        commentContent.setText(recordsBean.getContent() + "");
        //是否是作者的展示isOwner = 1是作者  = 0为不是作者
        if (recordsBean.getIsOwner() == 1) {
            oneAuthor.setVisibility(View.VISIBLE);
        } else {
            oneAuthor.setVisibility(View.GONE);
        }
        //一级评论时间
        commentTime.setText(DateUtils.getDayTimeUtils(recordsBean.getCreateTime())+"");
        if (recordsBean.getRecords() == null) {
            recordsBean.setRecords(new ArrayList<>());
        }
        //自动打开弹窗标记
        if (type==2){
           if (position==0){
               if (ids.equals(datas.get(position).getId())){
                   llContentbg.setBackgroundColor(context.getResources().getColor(R.color.color_main_bg));
               }else {
                   llContentbg.setBackgroundColor(context.getResources().getColor(R.color.white));
               }
               llContentbg.setBackgroundColor(context.getResources().getColor(R.color.color_main_bg));
           }else {
               llContentbg.setBackgroundColor(context.getResources().getColor(R.color.white));
           }
        }
        if (isFirst && type == 2) {
            isFirst = false;
            if (recordsBean.getRecords().size() > 3) {
                recordsBean.setTempSize(3);
            } else {
                recordsBean.setTempSize(-1);
            }
        }
        //是否点赞
        if (recordsBean.getIsLike()==2){
            imCommentZan.setImageResource(R.mipmap.share_comment_yes_zan);
            commentZanNum.setTextColor(context.getResources().getColor(R.color.color_FF3960));
        }else{
            imCommentZan.setImageResource(R.mipmap.share_comment_no_zan);
            commentZanNum.setTextColor(context.getResources().getColor(R.color.color_tab_two));
        }
        //一级点赞数量
        commentZanNum.setText(datas.get(position).getCommentLaudCount()+"");
        // 加载二级数据
        SecondLevelCommentAdapter adapter = new SecondLevelCommentAdapter(context, recordsBean.getRecords(), recordsBean.getTempSize(),type,ids);
        listView.setLayoutManager(new LinearLayoutManager(context));
        listView.setAdapter(adapter);
        listView.setNestedScrollingEnabled(false);
        adapter.setCallback(new SecondLevelCommentAdapter.ActionCallback() {

            @Override
            public void onChildLongClick(VideoCommentListEntity.RecordsBeanX.RecordsBean holder, int pos) {
                //delPermission  删除权限：1：无，2：有
                if (holder.getDelPermission() == 2) {
                    mQueMap = new HashMap<>();
                    mQueMap.put("id", holder.getId());
                    mCurQuePos = position;
                    mCurQueChildPos = pos;
                    if (callback != null) {
                        callback.delete();
                    }
                }else {
                    MToast.showToast(context,"没有删除此评论权限");
                }

            }


            @Override
            public void onChildRely(VideoCommentListEntity.RecordsBeanX.RecordsBean holder, int pos) {
                mQueMap = new HashMap<>();
                mQueMap.put("content", "");
                mQueMap.put("videoId", holder.getVideoId());
                mQueMap.put("parentId", holder.getParentId());
                mQueMap.put("receiveUser", holder.getUser());
                mQueMap.put("replyId", holder.getId());
                mType = 2;
                mCurQuePos = position;
                if (callback != null) {
                    callback.onShowSoftKey();
                }
            }

            @Override
            public void onChildPraise(VideoCommentListEntity.RecordsBeanX.RecordsBean holder, int pos) {
                Map map =new HashMap<>();
                map.put("type",2);
                if (holder!=null){
                    map.put("videoId",holder.getId());
                }
                getLikeVideoComment(map,position,pos,2);
            }
        });

        //默认是否加载二级数据
        if (recordsBean.isOneComment()) {
            if (recordsBean.getRecords().size() > 0) {
                llSeeMore.setVisibility(View.GONE);
                listView.setVisibility(View.VISIBLE);
                llTwoSeeMore.setVisibility(View.VISIBLE);
            } else {
                llSeeMore.setVisibility(View.GONE);
                listView.setVisibility(View.GONE);
                llTwoSeeMore.setVisibility(View.GONE);
            }
            //判断二级数据是加载完成，根据加载情况动态添加是否查看更多或者手气
            if (recordsBean.getRecords().size() >= recordsBean.getReplyCount()+recordsBean.getAddComment()) {
                unwindTwoNumReply.setText("收起");
                imJiantou.setImageResource(R.mipmap.share_shouqi);
            } else {
                unwindTwoNumReply.setText("查看更多");
                imJiantou.setImageResource(R.mipmap.share_zhankai);
            }
        } else {
            //为false时默认关闭，关闭分为
            if (datas.get(position).getTempSize() > 0) {
                listView.setVisibility(View.VISIBLE);
                llTwoSeeMore.setVisibility(View.GONE);
            } else {
                listView.setVisibility(View.GONE);
                llTwoSeeMore.setVisibility(View.GONE);
            }
            //二级评论的数量
            if (recordsBean.getReplyCount() > 0) {
                llSeeMore.setVisibility(View.VISIBLE);
                unwindNumReply.setText(String.format("展开%s条回复", recordsBean.getReplyCount()));
            } else {
                llSeeMore.setVisibility(View.GONE);
            }
        }
        //点击展开多少条评论
        llSeeMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datas.get(position).setOneComment(true);
                datas.get(position).setTempSize(-1);
                notifyItemChanged(position);
            }
        });
        //二级差看更多
        llTwoSeeMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean equals = "收起".equals(unwindTwoNumReply.getText().toString());
                if (equals) {
                    datas.get(position).setReplyCount(datas.get(position).getRecords().size());
                    datas.get(position).setOneComment(false);
                    listView.setVisibility(View.GONE);
                    llTwoSeeMore.setVisibility(View.GONE);
                    llSeeMore.setVisibility(View.VISIBLE);
                    unwindNumReply.setText(String.format("展开%s条回复", recordsBean.getReplyCount()));
                } else {
                    if (datas.get(position).getRecords().size() > 0) {
                        StringBuilder src = new StringBuilder();
                        for (int i = 0; i < datas.get(position).getRecords().size(); i++) {
                            src.append(",").append(datas.get(position).getRecords().get(i).getId());
                        }
                        SeeModeComment(datas.get(position), src.toString(), position);
                    } else {
                        SeeModeComment(datas.get(position), "", position);
                    }
                }
            }
        });
        //一级评论回复
        commentReply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                VideoCommentListEntity.RecordsBeanX recordsBeanX = datas.get(position);
                mQueMap.clear();
                mQueMap = new HashMap<>();
                mQueMap.put("content", "");
                mQueMap.put("videoId", recordsBeanX.getVideoId());
                mQueMap.put("parentId", recordsBeanX.getId());
                mQueMap.put("receiveUser", recordsBeanX.getUser());
                mQueMap.put("replyId", recordsBeanX.getId());
                mType = 1;
                mCurQuePos = position;
                if (callback != null) {
                    callback.onShowSoftKey();
                }
            }
        });
        // 一级删除的操作
        holder.itemView.findViewById(R.id.ll_one_comment).setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                //delPermission  删除权限：1：无，2：有
                if (datas.get(position).getDelPermission() == 2) {
                    mQueMap.clear();
                    mQueMap = new HashMap<>();
                    mQueMap.put("id", datas.get(position).getId());
                    mCurQuePos = position;
                    mCurQueChildPos = -1;
                    if (callback != null) {
                        callback.delete();
                    }
                }else {
                    MToast.showToast(context,"没有删除此评论权限");
                }
                return true;
            }
        });
        //一级点赞
        llCommentZan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            Map map =new HashMap<>();
            map.put("type",2);
            map.put("videoId",datas.get(position).getId());
            getLikeVideoComment(map,position,0,1);
            }
        });

        TextView hasMoreText = holder.itemView.findViewById(R.id.comment_nodata);
        hasMoreText.setVisibility(isVisibleMoreText && position == datas.size() - 1 ?View.VISIBLE :View.GONE);
    }

    @Override
    public void convert(ItemViewHolder holder, VideoCommentListEntity.RecordsBeanX recordsBean) {
    }

    public void setVisibleMoreText(boolean visibleMoreText) {
        isVisibleMoreText = visibleMoreText;
    }

    public void setCallback(CommentCallback callback) {
        this.callback = callback;
    }

    public void loadMoreChildData(int pos, List<VideoCommentListEntity.RecordsBeanX.RecordsBean> records) {
        int page = mPageArray.get(pos);
        mPageArray.put(pos, page + 1);
        if (datas.get(pos).getRecords().size() > 0) {
            datas.get(pos).getRecords().addAll(records);
        } else {
            datas.get(pos).setRecords(records);
        }
        notifyItemChanged(pos);
      /*  if (callback != null) {
            callback.onLoadSuccess();
        }*/
    }

    // 一级回复
    public void loadData(int pos, VideoCommentListEntity.RecordsBeanX recordsBeanX) {
        datas.add(0, recordsBeanX);
        datas.get(0).setOneComment(false);
        setVisibleMoreText(true);
        notifyDataSetChanged();
        if (callback != null) {
            callback.onLoadSuccess();
        }
    }

    // 二级回复
    public void loadChildRelyData(int pos, VideoCommentListEntity.RecordsBeanX.RecordsBean records) {
        boolean oneComment = datas.get(pos).isOneComment();
        datas.get(pos).getRecords().add(0, records);
        datas.get(pos).setAddComment(datas.get(pos).getAddComment()+1);
        if (oneComment) {
            datas.get(pos).setTempSize(-1);
        } else {
            int tempSize = datas.get(pos).getTempSize();
            if(tempSize == -1){
                datas.get(pos).setTempSize(1);
            } else {
                datas.get(pos).setTempSize(tempSize + 1);
            }
        }
        notifyItemChanged(pos);
        if (callback != null) {
            callback.onLoadSuccess();
        }
    }

    // 点赞评论
    public void loadChildLikesData(int pos,int twopos,int type,Long likes) {
        if (type==1){
            //给列表一设置数据、根据状态设置数量
            if (datas.get(pos).getIsLike()==2){
                datas.get(pos).setIsLike(1);
            }else {
                datas.get(pos).setIsLike(2);
            }
            datas.get(pos).setCommentLaudCount(likes);
        }else {
            //给列表二设置数据、根据状态设置数量
            if (datas.get(pos).getRecords().get(twopos).getIsLike()==2){
                datas.get(pos).getRecords().get(twopos).setIsLike(1);
            }else {
                datas.get(pos).getRecords().get(twopos).setIsLike(2);
            }
            datas.get(pos).getRecords().get(twopos).setCommentLaudCount(likes);

        }
        notifyItemChanged(pos);
    }

    public void deleteData(int parentPos, int childPos) {
        if (callback != null) {
            callback.deleteSucceed();
        }
    }

    public void rely(String content, String videoid, String CreateUser) {
        mQueMap.put("content", content);
        if (mType == 0) {
            mQueMap = new HashMap<>();
            mQueMap.put("videoId", videoid);
            mQueMap.put("parentId", 0);
            mQueMap.put("receiveUser", CreateUser);
            mQueMap.put("replyId", 0);
            mQueMap.put("content", content);
            getOnwAddVideoComment(mQueMap, 0);
            return;
        }
        getAddVideoComment(mQueMap, mCurQuePos);
    }

    public void setType(int mType) {
        this.mType = mType;
    }

    //获取展开二级评论
    private void SeeModeComment(VideoCommentListEntity.RecordsBeanX recordsBeanX, String comments, int pos) {
        int page = mPageArray.get(pos);
        if (page == 0) {
            page = 1;
            mPageArray.put(pos, 1);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("parentId", recordsBeanX.getId());
        map.put("id", comments);
        map.put("pageNum", page);
        map.put("pageSize", 10);
        DialogHelper.showProgressDialog(context, null, "加载中...", 0, true, null).setCanceledOnTouchOutside(false);
       ShareConfig.getInstance().getApi().apiGetVideoReplyList(map).enqueue(new Callback<BaseEntity<VideoCommentListEntity.RecordsBeanX>>() {
            @Override
            public void onResponse(Call<BaseEntity<VideoCommentListEntity.RecordsBeanX>> call, Response<BaseEntity<VideoCommentListEntity.RecordsBeanX>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(ShareConfig.RESPONSE_OK)) {
                    List<VideoCommentListEntity.RecordsBeanX.RecordsBean> records = response.body().getData().getRecords();
                    if (records == null) return;
                    loadMoreChildData(pos, records);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<VideoCommentListEntity.RecordsBeanX>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //新增一级
    public void getOnwAddVideoComment(Map<String, Object> map, int pos) {
        DialogHelper.showProgressDialog(context, null, "提交中...", 0, true, null).setCanceledOnTouchOutside(false);
        ShareConfig.getInstance().getApi().addVideoComment(map).enqueue(new Callback<BaseEntity<VideoCommentListEntity.RecordsBeanX>>() {
            @Override
            public void onResponse(Call<BaseEntity<VideoCommentListEntity.RecordsBeanX>> call, Response<BaseEntity<VideoCommentListEntity.RecordsBeanX>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(ShareConfig.RESPONSE_OK)) {
                    VideoCommentListEntity.RecordsBeanX data = response.body().getData();
                    loadData(pos, data);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<VideoCommentListEntity.RecordsBeanX>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //新增二级
    public void getAddVideoComment(Map<String, Object> map, int pos) {
        DialogHelper.showProgressDialog(context, null, "提交中...", 0, true, null).setCanceledOnTouchOutside(false);
        ShareConfig.getInstance().getApi().addSecondVideoComment(map).enqueue(new Callback<BaseEntity<VideoCommentListEntity.RecordsBeanX.RecordsBean>>() {
            @Override
            public void onResponse(Call<BaseEntity<VideoCommentListEntity.RecordsBeanX.RecordsBean>> call, Response<BaseEntity<VideoCommentListEntity.RecordsBeanX.RecordsBean>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(ShareConfig.RESPONSE_OK)) {
                    VideoCommentListEntity.RecordsBeanX.RecordsBean data = response.body().getData();
                    loadChildRelyData(pos, data);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<VideoCommentListEntity.RecordsBeanX.RecordsBean>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //删除当前评论信息
    public void deleteComment() {
        DialogHelper.showProgressDialog(context, null, "删除中...", 0, true, null).setCanceledOnTouchOutside(false);
        ShareConfig.getInstance().getApi().apiDeleteCommentById(mQueMap).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(ShareConfig.RESPONSE_OK)) {
                    deleteData(mCurQuePos, mCurQueChildPos);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //评论点赞
    public void getLikeVideoComment(Map<String, Object> map, int pos,int twoPos,int type) {
        ShareConfig.getInstance().getApi().getlikes(map).enqueue(new Callback<BaseEntity<Long>>() {
            @Override
            public void onResponse(Call<BaseEntity<Long>> call, Response<BaseEntity<Long>> response) {
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(ShareConfig.RESPONSE_OK)) {
                    loadChildLikesData(pos,twoPos, type,response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<Long>> call, Throwable t) {
            }
        });
    }

    public interface CommentCallback {
        void onShowSoftKey();

        void delete();

        void deleteSucceed();

        void onLoadSuccess();
    }

}
